package nacos

import (
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/v2/model"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"

	"github.com/go-kit/kit/log"
)

var logger log.Logger

type IClient interface {
	Register(r vo.RegisterInstanceParam) (bool, error)
	Deregister(r vo.DeregisterInstanceParam) (bool, error)
	Service(r vo.GetServiceParam) (model.Service, error)
	GetInstances(r vo.SelectInstancesParam) ([]model.Instance, error)
}

type client struct {
	nacos naming_client.INamingClient
}

func NewClient(param vo.NacosClientParam) IClient {
	// 创建服务发现客户端的另一种方式 (推荐)
	nc, err := clients.NewNamingClient(
		param,
	)

	if err != nil {
		logger.Log("连接nacos客户端出错：", err.Error())
		return nil
	}
	return &client{nacos: nc}
}

func (c *client) Register(r vo.RegisterInstanceParam) (bool, error) {
	return c.nacos.RegisterInstance(r)
}

func (c *client) Deregister(r vo.DeregisterInstanceParam) (bool, error) {
	return c.nacos.DeregisterInstance(r)
}

func (c *client) Service(r vo.GetServiceParam) (model.Service, error) {
	return c.nacos.GetService(r)
}

func (c *client) GetInstances(r vo.SelectInstancesParam) ([]model.Instance, error) {
	return c.nacos.SelectInstances(r)
}